import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import { Certificate } from './entities/certificate.entity';
import { CreateCertificateDto } from './dto/create-certificate.dto';
import { UpdateCertificateDto } from './dto/update-certificate.dto';

@Injectable()
export class CertificateService {
  constructor(
    @InjectRepository(Certificate)
    private certificateRepository: Repository<Certificate>,
  ) {}

  async create(createCertificateDto: CreateCertificateDto) {
    const certificate = this.certificateRepository.create(createCertificateDto);
    return await this.certificateRepository.save(certificate);
  }

  async findAll() {
    return await this.certificateRepository.find();
  }

  async findOne(id: number) {
    return await this.certificateRepository.findOne({ where: { id } });
  }

  async update(id: number, updateCertificateDto: UpdateCertificateDto) {
    await this.certificateRepository.update(id, updateCertificateDto);
    return await this.certificateRepository.findOne({ where: { id } });
  }

  async remove(id: number) {
    return await this.certificateRepository.delete(id);
  }
  async getList(query: any = {}) {
    const { page, size, title = '' } = query;
    const searchObj = {
      // 根据关键词模糊查询
      where: {
        title: Like(`%${title}%`),
      },
      // 根据分页信息查询
      skip: (page - 1) * size, // 从第x页开始，需要x条数据
      take: size,
    };

    const totalNum = {
      where: {
        title: Like(`%${title}%`),
      },
    };

    const data = await this.certificateRepository.find(searchObj);
    const total = await this.certificateRepository.count(totalNum);
    // 从数据库中获取结果，并作为响应返回
    return {
      data,
      total,
    };
  }
}
